package com.itic.appbase.applications.sys.code.controller;

import java.beans.IntrospectionException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.sys.code.persistence.model.Code;
import com.itic.appbase.applications.sys.code.persistence.model.CodeExample;
import com.itic.appbase.applications.sys.code.persistence.model.CodeExample.Criteria;
import com.itic.appbase.applications.sys.code.service.CodeService;
import com.itic.appbase.framework.common.constants.DBConst;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.ParameterErrorException;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.ValueHelper;

/**
 * 代码表管理
 * <p>
 * Company: itic
 * </p>
 * 
 * @author: shijun
 * @date: 2015年5月15日 上午10:40:17
 * @version: V1.0
 */
@Controller
@RequestMapping(value = "/sys/code")
public class CodeController
        extends BaseController {
    @Autowired
    private CodeService codeService;

    // 返回属性黑名单
    private static String[] ignoreProperties = new String[] { "createUser", "isEffective", "orgCode", "createTime",
            "updateTime" };

    /**
     * 非级联代码表主页面
     * 
     * @return
     */
    @RequestMapping(value = "/init")
    public String init() {
        return "sys/code/codeMain";
    }

    /**
     * 新增页面
     * 
     * @return
     */
    @RequestMapping(value = "/initAdd")
    public String initAdd() {
        return "sys/code/codeAdd";
    }

    /**
     * 编辑页面
     * 
     * @return
     */
    @RequestMapping(value = "/initEdit")
    public String initEdit(String id, Model model) {
        if (StringHelper.isNoneBlank(id)) {
            Code code = codeService.get(id);
            model.addAttribute(code);
        } else {
            throw new ParameterErrorException();
        }

        return "sys/code/codeEdit";
    }

    /**
     * 数据列表展示
     * 
     * @param code
     * @param request
     * @return
     * @throws IntrospectionException
     * @throws InvocationTargetException
     * @throws IllegalAccessException
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Map<String, Object> list(Code code, HttpServletRequest request){
        // 声明返回对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        // 参数处理
        CodeExample codeExample = new CodeExample();
        // 封装分页参数
        codeExample = this.handlePageQuery(request, codeExample);
        // 封装查询条件
        codeExample = queryCondition(code, codeExample);
        // 获取数据
        List<Code> roleList = codeService.list(codeExample);
        // 返回属性处理
        List<Map<String, Object>> resultList = ValueHelper.tranList2MapList(roleList, ignoreProperties);
        // 获取数据总数
        int totalNum = codeService.count(codeExample);
        // 数据返回处理
        resultMap.put(IticConst.TOTAL_RECORDS, totalNum); // 总记录
        resultMap.put(IticConst.DISPLAY_RECORDS, totalNum);
        resultMap.put(IticConst.DATA, resultList);
        resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());
        return resultMap;
    }

    /**
     * 代码表新增
     * 
     * @param code
     * @return
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public Map<String, Object> add(Code code) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (null != code && StringHelper.isNotBlank(code.getCode())) {
            // 将代码转换为大写
            code.setCode(code.getCode().toUpperCase());
            result = codeService.add(code);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 代码表修改
     * 
     * @param code
     * @return
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public Map<String, Object> edit(Code code) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (null != code && StringHelper.isNotBlank(code.getCode())) {
            result = codeService.edit(code);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 删除代码
     * 
     * @param ids
     * @param codes
     *            清除缓存用参数
     * @return
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public Map<String, Object> delete(String ids) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        String result = ResponseCode.SERVER_ERROR.getCode();
        if (StringHelper.isNotBlank(ids)) {
            List<String> idList = Arrays.asList(ids.trim().split(","));// codeid
            // 删除代码表信息
            CodeExample codeExample = new CodeExample();
            codeExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE).andIdIn(idList);
            Code code = new Code();
            code.setUpdateTime(new Date());
            code.setIsEffective(DBConst.FALSE);
            // 查找id对应的type集合,方便删除缓存
            List<Code> codeList = codeService.list(codeExample);
            List<String> typeList = new ArrayList<String>();
            for (Code c : codeList) {
                typeList.add(c.getCode());
            }
            // 执行删除
            result = codeService.delete(code, codeExample, idList, typeList);
        } else {
            result = ResponseCode.PARAM_INVALID.getCode();
        }
        resultMap.put(IticConst.RESULT, result);
        return resultMap;
    }

    /**
     * 校验代码表code是否重复
     * 
     * @param code
     * @return
     */
    @RequestMapping(value = "/checkCodeExist")
    @ResponseBody
    public Map<String, Object> checkCodeExist(Code code) {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        if (null != code) {
            CodeExample codeExample = new CodeExample();
            // 封装查询条件
            Criteria criteria = codeExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
            if (StringHelper.isNotBlank(code.getCode())) {// 代码表代码
                criteria.andCodeEqualTo(code.getCode().toUpperCase());
            }
            if (StringHelper.isNotBlank(code.getId())) {// 去掉重复代码，过滤掉自身
                criteria.andIdNotEqualTo(code.getId());
            }
            // 获取结果数据
            List<Code> roleList = codeService.list(codeExample);
            if (null != roleList && !roleList.isEmpty()) {
                resultMap.put(IticConst.RESULT, ResponseCode.EXIST.getCode());// 代码表代码已存在
            } else {
                resultMap.put(IticConst.RESULT, ResponseCode.SUCCESS.getCode());// 代码表代码可用
            }
        } else {
            resultMap.put(IticConst.RESULT, ResponseCode.PARAM_INVALID.getCode());// 参数不合法
        }
        return resultMap;
    }

    /**
     * 封装查询条件
     * 
     * @param code
     * @param codeExample
     * @return CodeExample
     */
    private CodeExample queryCondition(Code code, CodeExample codeExample) {
        codeExample.setOrderByClause("name asc");
        // 封装查询条件
        Criteria criteria = codeExample.createCriteria().andIsEffectiveEqualTo(DBConst.TRUE);
        if (null != code) {
            if (StringHelper.isNotBlank(code.getName())) {// 代码表名称
                criteria.andNameLike("%" + code.getName() + "%");
            }
            if (StringHelper.isNotBlank(code.getCode())) {// 代码表代码
                criteria.andCodeLike("%" + code.getCode() + "%");
            }
            if (StringHelper.isNotBlank(code.getType())) {// 是否级联，1：级联；0：非级联
                criteria.andTypeEqualTo(code.getType());
            }
        }
        return codeExample;
    }
}